package com.bcx.wind.workflow.interceptor;

import com.bcx.wind.workflow.pojo.Wind;

import java.lang.reflect.Method;

/**
 * 业务执行拦截器
 *
 * @author zhanglei
 */
public class InvokeInterceptor extends AbstractCommandInterceptor {

    /**
     * 命令执行数据
     */
    private CommandContext commandContext;

    public InvokeInterceptor(CommandContext context){
        this.commandContext = context;
    }

    @Override
    public CommandInterceptor getNext() {
        return null;
    }

    @Override
    public <T> T executor(Command<T> command) {
        T t =  command.executor(commandContext);
        //执行后置拦截器
        if( t instanceof Wind && commandContext.getConfiguration().getAfterInterceptor() != null){
            AfterInterceptor interceptor = commandContext.getConfiguration().getAfterInterceptor();
            interceptor.invoke((Wind) t,this.commandContext);
        }
        if(t == null){
            printError(command);
        }
        return t;
    }


    @SuppressWarnings("unchecked")
    private  void  printError(Command command){
        try {
            Method method = command.getClass().getMethod("executor", CommandContext.class);
            if(method != null){
                Class aClass = method.getReturnType();
                if (!aClass.isAssignableFrom(Void.class)) {
                    this.logger.error(null,new Throwable());
                }
            }
        } catch (NoSuchMethodException e) {
            this.logger.error(null,new Throwable());
        }
    }


    @Override
    public void setNext(CommandInterceptor next) {
        throw new UnsupportedOperationException("workflow invokeInterceptor must be last interceptor! ");
    }


}
